/**
 * 用户管理
 */
const router = require('koa-router')()
const User = require('../models/userSchema')
const Role = require('../models/roleSchema')
const util = require('../utils/util')
const jwt = require('jsonwebtoken')
const log4js = require('../utils/log4j')
const md5 = require('md5')

router.prefix('/roles')

// 所有的角色列表
router.get('/allList', async ctx => {
  try {
    let list = await Role.find({}, '_id roleName');
    ctx.body = util.success(list);
  } catch (error) {
    ctx.body = util.fail(`查询失败 ${error.stack}`);
  }
})

// 分页获取角色列表
router.get('/list', async (ctx) => {
  const { roleName, pageNum, pageSize } = ctx.request.query;
  const { page, skipIndex } = util.pager({ pageNum, pageSize });
  try {
    const params = {}
    if (roleName) params.roleName = roleName;
    const query = Role.find(params);
    const list = await query.skip(skipIndex).limit(page.pageSize);
    const total = await Role.countDocuments(roleName);
    ctx.body = util.success({
      list, page: {
        ...page,
        total
      }
    })
  } catch (error) {
    ctx.body = util.fail(`查询失败 ${error.stack}`)
  }
})

router.post('/update/permission', async (ctx) => {
  const { _id, permissionList } = ctx.request.body;
  try {
    if (!_id) {
      ctx.body = util.fail(`请提供 _id`);
      return
    }
    await Role.findByIdAndUpdate(_id, { permissionList });
    ctx.body = util.success('')
  } catch (error) {
    ctx.body = util.fail(`修改失败 ${error.stack}`)
  }
})

router.post('/operate', async (ctx) => {
  const { action, _id, roleName, remark, } = ctx.request.body;
  try {
    let msg = ''
    let res = {};
    if (action === 'add') {
      res = await Role.create({ roleName, remark });
      msg = '新增成功'
    } else if (action === 'edit') {
      if (!_id) {
        ctx.body = util.fail('缺少参数 _id')
        return
      }
      res = await Role.findByIdAndUpdate(_id, { roleName, remark, });
      msg = '修改成功'
    } else if (action === 'delete') {
      res = await Role.findByIdAndDelete(_id);
      msg = '删除成功'
    }
    ctx.body = util.success(res, msg);
    return;
  } catch (error) {
    ctx.body = util.fail(`操作失败 ${error.stack}`)
  }
})

module.exports = router
